#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import datetime
from django.utils import simplejson
import cgi

from model import Question
from model import QuestionAnswer


class MyHandler(webapp.RequestHandler):
    
    def get(self):
        form = cgi.FieldStorage()
        question = Question.get(form.getvalue("question"))
        # figure out how to get this
        userid = int(form.getvalue("userID"))
        answer = form.getvalue("answer")
        if not answer in question.answers:
            self.response.out.write("invalid answer")
            return
        
        AnsweredQuestions = db.Query(QuestionAnswer).filter("question =", question).filter("userid =", userid)

        if AnsweredQuestions.count() > 0:
            self.response.out.write("already answered")
            return

        questionanswer = QuestionAnswer(answer = answer, userid = userid, question = question)
        questionanswer.put()

        self.response.out.write("success")

def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()